package com.ruoyi.Apps.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@Component
public class I18nUtil {

    private static MessageSource messageSource;

    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    /**
     * 获取国际化消息
     */
    public static String getMessage(String key, Object[] args, Locale locale) {
        try {
            return messageSource.getMessage(key, args, locale);
        } catch (Exception e) {
            return key; // 如果找不到对应的key，返回key本身
        }
    }

    /**
     * 从请求中获取Locale
     */
    public static Locale getLocaleFromRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String language = request.getHeader("language");
                if (language != null && !language.isEmpty()) {
                    return Locale.forLanguageTag(language.replace("_", "-"));
                }
            }
        } catch (Exception e) {
            // 忽略异常，使用默认locale
        }
        return Locale.SIMPLIFIED_CHINESE; // 默认zh_CN
    }
}
